package com.ultrapower.util.span;

import java.util.Comparator;

import com.ultrapower.bean.SpanEventBean;

public class SpanEventComparator implements Comparator<SpanEventBean> {

	public static final SpanEventComparator INSTANCE = new SpanEventComparator();

	@Override
	public int compare(SpanEventBean o1, SpanEventBean o2) {
		final int sequenceCompare = shortCompare(o1.getSequence(), o2.getSequence());
		if (sequenceCompare != 0) {
			return sequenceCompare;
		}
		final int asyncId1 = o1.getAsyncId();
		final int asyncId2 = o2.getAsyncId();
		final int asyncIdCompare = integerCompare(asyncId1, asyncId2);
		if (asyncIdCompare != 0) {
			// bug Comparison method violates its general contract!
			// TODO temporary fix
			// if (asyncId1 == -1) {
			// return -1;
			// }
			// if (asyncId2 == -1) {
			// return -1;
			// }
			return asyncIdCompare;
		}
		return integerCompare(o1.getAsyncSequence(), o2.getAsyncSequence());
	}

	public static int shortCompare(short x, short y) {
		return x - y;
	}

	public static int integerCompare(int x, int y) {
		return (x < y) ? -1 : ((x == y) ? 0 : 1);
	}

}
